package com.xc.hotelmgr.datahandlermt.controller;


import com.xc.hotelmgr.datahandlermt.pojo.mq.HotelCallBack;
import com.xc.hotelmgr.datahandlermt.pojo.mq.RatesCallBack;
import com.xc.hotelmgr.datahandlermt.pojo.mq.RpCallBack;
import com.xc.hotelmgr.datahandlermt.pojo.mybatis.HtDailyroom;
import com.xc.hotelmgr.datahandlermt.pojo.mybatis.HtHotelinfo;
import com.xc.hotelmgr.datahandlermt.pojo.mybatis.HtLogicRoom;
import com.xc.hotelmgr.datahandlermt.service.mybatis.HtHotelinfoService;
import com.xc.hotelmgr.datahandlermt.service.mybatis.HtLogicRoomService;
import com.xc.hotelmgr.datahandlermt.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequiredArgsConstructor
@Slf4j
public class SaveController {

    private final HtLogicRoomService htLogicRoomService;

    private final HtHotelinfoService htHotelinfoService;

    private final SendMessageMgr sendMessageMgr;

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 保存美团变化的房态后发送给飞猪推送服务推送
     * @param htDailyrooms
     * @return
     */
    @RequestMapping(value = "saveRates2MQ", method = RequestMethod.POST)
    public boolean saveRates2MQ(@RequestBody List<HtDailyroom> htDailyrooms) {

        List<String> dateList;
        Long rpCode = htDailyrooms.get(0).getRpCode();
        Integer num = htDailyrooms.get(0).getSaleNum();             // 用来判断是价格变更还是库存变更

        RatesCallBack ratesCallBack = new RatesCallBack();
        ratesCallBack.setRpCode(rpCode);
        String hk;
        if(num!=null) {  // 库存变化 hk=n
            hk = "n";
        }else {          // 价格变化 hk=p
            hk = "p";
        }
        dateList = ratesToCache(htDailyrooms, hk);
        if(!dateList.isEmpty()) {
            ratesCallBack.setDates(dateList);
            sendMessageMgr.sendMessage(MqType.CALLBACKRATES, ratesCallBack, "");
        }
        return true;
    }

    @RequestMapping(value = "saveRp2MQ", method = RequestMethod.POST)
    public boolean saveRp2MQ(@RequestBody List<HtLogicRoom> htLogicRooms) {
        boolean result = htLogicRoomService.updateBatchById(htLogicRooms);
        if(result) {
            for (HtLogicRoom htLogicRoom : htLogicRooms) {
                RpCallBack rpCallBack = new RpCallBack();
                rpCallBack.setRpId(htLogicRoom.getId());
                sendMessageMgr.sendMessage(MqType.CALLBACKRP, rpCallBack, "");
            }
            return true;
        }
        return false;
    }

    @RequestMapping(value = "saveHotel2MQ", method = RequestMethod.POST)
    public boolean saveHotel2MQ(@RequestBody List<HtHotelinfo> htHotelinfos) {
//        boolean result = htHotelinfoService.updateBatchById(htHotelinfos);
//        if(result) {
            for (HtHotelinfo htHotelinfo:htHotelinfos) {
                HotelCallBack hotelCallBack = new HotelCallBack();
                hotelCallBack.setHotelId(htHotelinfo.getId());
                sendMessageMgr.sendMessage(MqType.CALLBACKHOTEL, hotelCallBack, "");
            }
            return true;
//        }
//        return false;
    }

    private List<String> ratesToCache(List<HtDailyroom> htDailyrooms, String hk) {
        List<String> dateList = new ArrayList<>();
        RedisConnection connection = null;
        try {
            // ··························开启redis管道·······································
            connection = redisTemplate.getConnectionFactory().getConnection();
            connection.openPipeline();
            // ··············································································

            // ····························当前日期···································
            String curDateStr = DateUtils.format(new Date(),"yyyy-MM-dd");
            Date curDate = DateUtils.stringToDate(curDateStr,"yyyy-MM-dd");
            // ······································································
            Long expire; // 失效时间

            for (HtDailyroom hdr:htDailyrooms) {
                Date ratesDate = hdr.getPriceDate();         // 价态量日期
                expire = (DateUtils.suDates(ratesDate,curDate) + 1)*24*60*60*1000; // redis缓存失效时间
                Map<byte[],byte[]> map = new HashMap<>();   // 需要存入的价态量。。

                String h = "r" + hdr.getId();    // redisHash h
                if(hk.equals("n")) {
                    map.put(hk.getBytes(), hdr.getSaleNum().toString().getBytes());
                }else {
                    map.put(hk.getBytes(), hdr.getPrice().toString().getBytes());
                }

                connection.hMSet(h.getBytes(),map);
                connection.pExpire(h.getBytes(),expire);

                dateList.add(ComUtil.dateToStr(ratesDate));
            }
        }catch (RuntimeException e) {
            log.error("缓存rates失败 " + e.getMessage());
            if(connection!=null) {
                connection.closePipeline();
            }
            return dateList;
        }
        connection.closePipeline();
        return dateList;
    }
}
